package cron

import (
	"bytes"
	"context"
	"encoding/json"
	"log"
	"math/rand"
	"net/http"
	"time"

	// "gitee.com/rogax/kagent/pkg/lldp"
	"gitee.com/rogax/kagent/pkg/types"
)

func generate(css []types.CronService) string {
	if len(css) == 0 {
		return ""
	}
	data := make(map[string]interface{})
	temp := make(map[string]interface{})

	for _, cs := range css {
		if d, err := cs.Get(); err != nil {
			log.Println(err)
		} else {
			if json.Unmarshal([]byte(d), &temp) != nil {
				log.Println("解析json数据失败: ", err)
			} else {
				for k, v := range temp {
					data[k] = v
				}
			}
		}
	}

	rsp, err := json.Marshal(data)
	if err != nil {
		log.Println(err)
		return ""
	}
	return string(rsp)
}

func Cron(ctx context.Context, t time.Duration, remote_url string, css []types.CronService) {
	randomInt := rand.Intn(30)
	time.Sleep(time.Duration(randomInt) * time.Second)

	var rsp string
	// data['lldp'] = interface{}(nil)
	ticker := time.NewTicker(t)
	defer ticker.Stop()
	for {
		// log.Println("Cron waiting...")

		select {
		case <-ctx.Done():
			log.Println("Cron stop")
			return
		case st := <-ticker.C:
			log.Printf("Cron starting: %s", st)
			rsp = generate(css)
			if rsp == "" {
				log.Println("定时任务获取数据失败")
			}
			// l := make(map[string]interface{})
			// json.Unmarshal([]byte(rsp), &data)
			// data['lldp'] = l['lldp']
			d, err := json.Marshal(rsp)
			if err != nil {
				log.Println(err)
				return
			}

			buffer := bytes.NewBuffer(d)
			resp, err := http.Post(remote_url, "application/json", buffer)
			if err != nil {
				log.Println(err)
				continue
			}
			resp.Body.Close()
			log.Printf("Cron finished, response code is: %d", resp.StatusCode)
			// default:
			// 	log.Println("cron waiting...")
		}
	}
}
